package com.itheima.ms.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.itheima.ms.enums.DBRoleEnum;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态切换数据源配置类
 */
@Configuration
public class SwitchDataSourceConfig {

    @ConfigurationProperties(prefix = "spring.datasource.druid.master-db")
    @Bean("master")
    public DataSource master(){
        return DruidDataSourceBuilder.create().build();
    }

    @ConfigurationProperties(prefix = "spring.datasource.druid.slave-db")
    @Bean("slave")
    public DataSource slave(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource dataSource(@Qualifier("master") DataSource master,@Qualifier("slave") DataSource slave){
        Map<DBRoleEnum,DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put(DBRoleEnum.MASTER,master);
        dataSourceMap.put(DBRoleEnum.SLAVE,slave);
        return new MyDynamicDataSource(master,dataSourceMap);
    }
}
